/**
 * 项目分类操作模块
 */
const Sequelize = require('sequelize')
const sequelize = require('../db/dbconfig')
const url = require('url')
const fs = require('querystring');
const ProjectCateModel = require('../db/models/project_cates')
const projectCateModel = ProjectCateModel(sequelize)
const Op = Sequelize.Op

// 添加项目分类
exports.addProjectCate = async (req, res) => {
  try {
    const projectCate = req.body
    let is_exist = await projectCateModel.findOne({
      where: {
        is_delete: 0,
        cate_name: projectCate.cate_name
      }
    })
    if(is_exist !== null) return res.myMsg('项目分类添加失败，项目分类已存在')
    let results = await projectCateModel.create({
      cate_name: projectCate.cate_name
    })
    res.myMsg('项目分类添加成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}

// 删除项目分类
exports.deleteProjectCate = async (req, res) => {
  try {
    let results = await projectCateModel.update({
    is_delete: 1
    },{
      where: {
        cate_id: req.params.id
      }
    })
    if(results[0] === 0) return res.myMsg('项目分类不存在')
    res.myMsg('项目分类删除成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}

// 修改项目分类
exports.updateProjectCate = async (req, res) => {
  try {
    const projectCate = req.body
    let is_exist = await projectCateModel.findOne({
      where: {
        is_delete: 0,
        cate_id: projectCate.cate_id
      }
    })
    if(is_exist === null) return res.myMsg('项目分类不存在')
    let results = await projectCateModel.update({
      cate_name: projectCate.cate_name
    },{
      where: {
        cate_id: projectCate.cate_id
      }
    })
    res.myMsg('项目分类修改成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}

// 查找项目分类
exports.getProjectCateAll = async (req, res) => {
  try {
    const {query} = url.parse(req.url, false);
    let temp = parseInt(fs.parse(query).offset[0])
    const offset = temp%2===0? temp:temp-1
    let results = await projectCateModel.findAndCountAll({
      where: {
        is_delete: 0
      },
      order: [
          ['cate_id','asc']
      ],
      limit: 2,
      offset
    })
    res.myMsg(results,0)
  } catch (e) {
    res.myMsg(e)
  }
}

// 查项目分类bycatename 模糊查询
exports.getProjectCateByCateName = async (req, res) => {
  try {
    const projectCate = req.body
    let results = await projectCateModel.findAll({
      where: {
        is_delete: 0,
        cate_name: {
          [Op.like]: `%${projectCate.cate_name}%`
        }
      }
    })
    if(results == '') return res.myMsg('查询失败，不存在该分类')
    res.myMsg(results,0)
  } catch (e) {
    res.myMsg(e)
  }
}